import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Row, Col, Card, Form, Input, Select, Button, DatePicker,Radio,Modal,message } from 'antd';
const { RangePicker } = DatePicker;
import AdminTable from '../../components/AdminTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './AdminList.less';
import docCookies from "../../common/DocCookies";
const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');

@connect(state => ({
  admin: state.admin,
}))
@Form.create()
export default class AdminList extends PureComponent {
  state = {
    addInputValue: '',
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    pageNo:1,
    pageSize:10,
    rsId:docCookies.getItem("rsId"),
    data:{},
    passwordModal:false,
    userId:null,
    title:'',
    initialStatus:"1",
    initialroleName:"0",
    password:true,
    confirmPassword:true,
    total:'',
    requireNameAndAccount:true,
    validateStatus:'',
    help:'',
    value:'',
    account:'',
  };

  componentDidMount() {
    this.loadAdminList();
  }

  loadAdminList(){
    const { dispatch } = this.props;
    const pageNo = this.state.pageNo ;
    const pageSize = this.state.pageSize ;
    // 需要传递的参数信息
    const params = {
      rsId:this.state.rsId,
      pageNo: pageNo,
      pageSize: pageSize,
    };
    // if(searchText) params.searchText=searchText;
    dispatch({
      type: 'admin/getAdmin',  //请求的action
      payload:params,
      callback:(data) =>{
        // console.log(data)
        this.setState({
          data:data.data,
          total:data.data.total
        })
      }
    });
  }

  //实现分页查询
  handlePageTableChange = (page, pageSize) => {
    this.setState({
      pageNo:page,
      pageSize:pageSize
    });
    this.loadAdminList();
  }

  handleFormReset = () => {
    const { form} = this.props;
    form.resetFields();
    this.setState({
      pageNo:1
    },() => {
      this.loadAdminList();
    });
  }


  handleModalVisible = (flag) => {
    if(flag === true) {
      this.setState({
        title:'新增',
        modalVisible: !!flag,
      })
    } else{
      this.clearForm();
      this.setState({
        modalVisible: flag,
        passwordModal:flag,
        editModal:flag
      })
    }
  }

  handleAdd = () => {
    const { form ,dispatch} = this.props;
    var me = this;
    form.validateFields(
      (err, values) => {
        if (!err) {
          if(this.state.validateStatus === "error"){
            message.error("该账号已被使用，请重新输入");
            return;
          }
          values.userId = this.state.userId;
          values.rsId = this.state.rsId;
          values.type = 1;
          if(values.password != undefined && values.password != "") {
            if(values.confirmPassword != values.password) {
              message.error("密码不一致");
              return;
            }
          } else {
            values.password = null;
          }
          // console.log(values)
          dispatch({
            type: 'admin/saveOrUpdateAccount',  //请求的action
            payload:values,
            callback:(res) =>{
              me.setState({
                modalVisible: false,
              });
              me.clearForm();
              me.loadAdminList();
              message.success(res.msg);
            }
          });
        }else{
          message.error("请将信息填写完整");
        }
      }
    );
  }

  clearForm(){
    this.props.form.resetFields();
    this.setState({
      initialStatus:"1",
      initialroleName:"0",
      password:true,
      confirmPassword:true,
      userId:null,
      requireNameAndAccount:true,
      validateStatus:"",
      help:'',
      value:'',
      account:'',
    });
  }

  handleChangePassword = () => {
    const { form ,dispatch} = this.props;
    var me = this;
    form.validateFields(
      (err, values) => {
        if (!err) {
          console.log(values)
          values.userId = this.state.userId;
          //type 区分仅修改密码或编辑功能  0 仅修改密码  1 编辑
          values.type = 0;
          values.rsId = this.state.rsId;
          values.account = values.account1;
          values.nickname = values.nickname1;
          dispatch({
            type: 'admin/saveOrUpdateAccount',  //请求的action
            payload:values,
            callback:(res) =>{
              me.setState({
                passwordModal: false,
              });
              me.clearForm();
              me.loadAdminList();
              message.success(res.msg);
            }
          });
        }else{
         message.error("请正确填写信息");
        }
      }
    );
  }


  /**
   * 确定两次密码输入一致
   * */
  handleConfirmPassword = (rule, value, callback) => {
    const { getFieldValue } = this.props.form;
    if (value && value !== getFieldValue('password')) {
      callback('两次输入不一致！')
    }else {
      callback()
    }
  }

  _changePassword = (record) => {
    const { form ,dispatch} = this.props;
    this.state.userId = record.userId;
    this.setState({
      passwordModal:true,
      requireNameAndAccount:false,
    })
    form.setFields({
      nickname1: {value: record.nickname},
      account1: {value: record.account},
    })
  }

  _editdata = (record) => {
    const { form ,dispatch} = this.props;
    this.state.userId = record.userId;
    // console.log(record)
    this.setState({
      password:false,
      confirmPassword:false,
      modalVisible:true,
      title:'编辑',
      initialStatus:record.status === 0 ? "0" : "1",
      initialroleName:record.roleName === '主播' ? "0" : "1",
      account:record.account,
      value:record.account,
    })
    form.setFields({
      nickname: {value: record.nickname},
      account: {value: record.account},
    })
  }

  _delAccount = (record) => {
    var me = this;
    const { dispatch} = this.props;
    var params = {};
    params.userId = record.userId;
    Modal.confirm({
      title: '提示',
      content: '您确定删除该账号吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'admin/delectAccount',  //请求的action
          payload:params,
          callback:(res) =>{
            me.loadAdminList();
            message.success(res.msg);
          }
        });
      }
    })
  }

  onBlur = () => {
    var me = this
    const {dispatch} = this.props;
    var value = this.state.value;
    if(value != null && value != undefined && value != ''){
      if(value != this.state.account) {
        var values={};
        values.account = value;
        dispatch({
          type: 'admin/validateAccountOnly',  //请求的action
          payload:values,
          callback:(res) =>{
            if(res.errorCode === 0){
              me.setState({
                validateStatus:"error",
                help:res.msg
              })
            } else {
              me.setState({
                validateStatus:"success",
                help:''
              })
            }
          }
        });
      }
    } else {
      me.setState({
        validateStatus:"error",
        help:'请输入账号'
      })
    }
  }


  onChange = (e) => {
    this.state.value = e.target.value;
  }




  render() {
    const { admin: { loading: loading} } = this.props;
    const { getFieldDecorator} = this.props.form;
    const { modalVisible,passwordModal} = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const extraCard = (
      <div>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)} >
          新增
        </Button>
      </div>
    )

    return (
      <PageHeaderLayout>
        <Card title="本台账号列表" bordered={false} extra={extraCard}>
          <div className={styles.tableList}>
            <AdminTable
              loading={loading}
              data={this.state.data}
              onChange={this.handlePageTableChange}
              changeKey={this._changePassword}
              editdata={this._editdata}
              pageNo={this.state.pageNo}
              pageSize={this.state.pageSize}
              total = {this.state.total}
              delectAccount={this._delAccount}
            />
          </div>
        </Card>

        <Modal
          title={this.state.title}
          visible={modalVisible}
          onOk={this.handleAdd}
          onCancel={() => this.handleModalVisible(false)}
        >
          <FormItem
            {...formItemLayout}
            label="姓名"
          >
            {getFieldDecorator('nickname', {
              rules: [{
                required:this.state.requireNameAndAccount, message: '请输入姓名',
              }],
            })(
              <Input placeholder="请输入姓名" />
            )}
          </FormItem>

          <FormItem
            hasFeedback
            {...formItemLayout}
            label="账号"
            help={this.state.help}
            validateStatus={this.state.validateStatus}
          >
            {getFieldDecorator('account', {
              rules: [{
                required: this.state.requireNameAndAccount, message: '请输入账号',
              }],
            })(
              <Input  onBlur={this.onBlur} onChange={this.onChange} placeholder="请输入账号" />
            )}
          </FormItem>


          {this.state.password?
            <FormItem
              {...formItemLayout}
              label="密码"
            >
              {getFieldDecorator('password', {
                rules: [{
                  required: this.state.password, message: '请输入密码',
                }],
              })(
                <Input placeholder="请输入密码" type="password" autoComplete="new-password"/>
              )}
            </FormItem>
            :null
          }

          {this.state.password?
            <FormItem
              {...formItemLayout}
              label="确认密码"
            >
              {getFieldDecorator('confirmPassword', {
                rules: [{
                  required: this.state.confirmPassword,
                  message: '密码不一致',
                  validator: this.handleConfirmPassword
                }],
              })(
                <Input placeholder="请输入确认密码" type="password"  autoComplete="new-password" />
              )}
            </FormItem>
            :null
          }

          <FormItem
            {...formItemLayout}
            label="角色"
          >
            {getFieldDecorator('roleName', {
              initialValue: this.state.initialroleName,
            })(
              <Radio.Group>
                <Radio value="0">主播</Radio>
                <Radio value="1">导播</Radio>
              </Radio.Group>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="状态"
          >
            {getFieldDecorator('status', {
              initialValue: this.state.initialStatus,
            })(
              <Radio.Group>
                <Radio value="1">正常</Radio>
                <Radio value="0">冻结</Radio>
              </Radio.Group>
            )}
          </FormItem>
        </Modal>

        <Modal
          title="修改密码"
          visible={passwordModal}
          onOk={this.handleChangePassword}
          onCancel={() => this.handleModalVisible(false)}
        >
          <FormItem
            {...formItemLayout}
            label="姓名"
          >
            {getFieldDecorator('nickname1')(
              <Input disabled={true}/>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="账号"
          >
            {getFieldDecorator('account1')(
              <Input disabled={true}/>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="密码"
          >
            {getFieldDecorator('password', {
              rules: [{
                required:this.state.password, message: '请输入密码',
              }],
            })(
              <Input placeholder="请输入密码" type="password" />
            )}
          </FormItem>

          <FormItem
            {...formItemLayout}
            label="确认密码"
          >
            {getFieldDecorator('confirmPassword', {
              rules: [{
                required: this.state.confirmPassword,
                message: '密码不一致',
                validator: this.handleConfirmPassword
              }],
            })(
              <Input placeholder="请输入确认密码" type="password"  autoComplete="new-password" />
            )}
          </FormItem>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
